﻿using System;
using System.Windows.Forms;

using DreamCube.Foundation.Basic.Utility;

namespace ShopHelper.BLL
{
    public class TB_ItemHtmlElement : ItemHtmlElement
    {
        public TB_ItemHtmlElement(HtmlElement element)
            : base(element)
        { }

        /// <summary>
        /// 判断指定的Html元素是否是商品元素
        /// </summary>
        /// <returns></returns>
        public override Boolean IsGoodElement()
        {
            //获取父html元素，也就是包含其图片的<a>标签
            if (String.Compare(this.htmlElement.TagName, "a", true) == 0)
            {
                String[] href = MyString.SubStringBetweenStr(this.htmlElement.OuterHtml, "href=\"", "\"", false, true);
                if (href == null || href.Length == 0) return false;
                return MyString.HasTargetStrStartWithItem(href[0], Properties.Resources.TB_GoodsUrlPrefix.Split(';'), StringComparison.CurrentCultureIgnoreCase);
            }
            return false;
        }

        /// <summary>
        /// 分析右键选中的html元素，得出基本的商品url信息
        /// </summary>
        /// <param name="itemTitle">商品的标题</param>
        /// <param name="itemTitle">商品的标题</param>
        /// <param name="from">商品的来源（天猫、淘宝、阿里巴巴、拍拍等等）</param>
        /// <param name="itemUrl"></param>
        /// <param name="itemID"></param>
        /// <returns></returns>
        public override Boolean ParseHtmlElement(out String itemTitle, out String from, out String itemUrl, out String itemID)
        {
            itemTitle = String.Empty;
            from = "淘宝网";
            itemUrl = String.Empty;
            itemID = String.Empty;
            HtmlDocument doc = this.htmlElement.Document;
            if (String.Compare(this.htmlElement.TagName, "a", true) != 0) return false;
            HtmlElementCollection hrefElements = doc.Body.GetElementsByTagName("a");
            itemUrl = this.htmlElement.GetAttribute("href");
            itemID = itemUrl.Substring(itemUrl.IndexOf("id=") + 3);
            for (Int32 i = 0, j = hrefElements.Count; i < j; i++)
            {
                if (String.Compare(hrefElements[i].TagName, "a", true) == 0
                    && hrefElements[i].InnerText != null
                    && !String.IsNullOrEmpty(hrefElements[i].InnerText.Trim()))
                {
                    String tempHref = hrefElements[i].GetAttribute("href");
                    if (tempHref.StartsWith(Properties.Resources.TB_GoodsUrlPrefix) && tempHref.IndexOf(itemID) >= 0)
                    {
                        itemTitle = hrefElements[i].InnerText;
                        return true;
                    }
                }
            }
            return false;
        }
    }
}
